# 异步爬取图片
# requests.get() 同步的代码 -> 异步操作 aiohttp
# pip install aiohttp

import time
import asyncio
import aiohttp

urls = [
    "https://kr.shanghai-jiuxin.com/file/2020/0627/c58410455f9f43d04fe2922e821693bb.jpg",
    "https://kr.shanghai-jiuxin.com/file/2020/0627/83d7cced86ee9902032e1e8000fdfd80.jpg",
    "https://kr.shanghai-jiuxin.com/file/2020/0627/46aa8f523b9d532882eaac90ab457058.jpg",
    "https://kr.shanghai-jiuxin.com/file/2020/0627/7344e144a8fc5118f2609b5df10d1bb1.jpg"
]


async def aiodownload(url):
    name = url.split("/", 6)[6]  # 切割图片名称

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:  # async with 异步请求不需要关闭连接
            # 请求回来了，写入文件
            # 可以自己去学习一个模块 aiofiles
            with open("../爬虫文件/03" + name, mode='wb') as file:
                file.write(await resp.content.read())  # await： 读取内容是异步的，需要 await 挂起操作


async def main():
    tasks = []
    # 一次性启动多个任务（协程）
    t1 = time.time()

    for url in urls:
        tasks.append(asyncio.create_task(aiodownload(url)))
    await asyncio.wait(tasks)

    await asyncio.wait(tasks)
    print('共耗时：', time.time() - t1)


if __name__ == '__main__':
    asyncio.run(main())
